/**
 * Created with Vim7.3 Mac
 * @fileOverview : 
 * @author : Lyle lylechen2014@gmail.com
 * @since : 2016-07-20 11:54:56
 * @filename : src/components/registerB.js
 * @version : 
 * @description : 
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Image,
  TextInput,
  TouchableOpacity,
  ActivityIndicator,
} from 'react-native';

import Icon from 'react-native-vector-icons/Ionicons';
import Tips from '../common/tips';
import LetsMeet from './letsMeet';

class RegisterB extends Component {

  doBool : false

  constructor(props) {
      super(props);
      this.state = {
           email:'',
           emailBool:true,
           username:'',
           usernameBool:true,
           password:'',
           passwordBool:true,
      	   postBool : false,
      }
  }
  
  shouldComponentUpdate(props,state) {
     this.checkContiune(state);
     return true;
  }

  postLoading() {
      let jsx = null;
      if (this.state.postBool) {
          jsx = <ActivityIndicator size="small" color="#fff"/>
      } else {
          jsx = <TouchableOpacity activeOpacity={1} onPress={()=>this.done()} >
                <Text suppressHighlighting={true} style={styles.buttonText}> Done </Text>
                </TouchableOpacity>
      }
      return (jsx);
  }

  render() {
      
      let postButton = this.postLoading();

  	  return (
        <View style={styles.container}>
            <View ref='tabB' style = {styles.tabB}>

              <View >
                  <Text suppressHighlighting={true} style = {styles.des}>
                      {Lang.reg_b_des}
                  </Text>
              </View>
         
                <View style={styles.inputText}  >
                    <TextInput
                          autoCapitalize = "none"
                          autoCorrect={false}
                          style={!this.state.emailBool ? [styles.input,styles.inputError] : styles.input}
                          placeholder = "Email"   
                          keyboardType = 'email-address'
                          clearButtonMode = 'while-editing'
                          textAlign = "left"
                          onChangeText = {(value) => this.onChangeEmail(value)}
                          onBlur = {() => {this.onBlurEmail()}}
                          />
                    <Image style={styles.imgbg} source={require('../img/date.png')} />
                </View>

                <View style={styles.inputText}  >
                    <TextInput
                          autoCapitalize = "none"
                          autoCorrect={false}
                          style={!this.state.usernameBool ? [styles.input,styles.inputError] : styles.input}
                          placeholder="Username" 
                          clearButtonMode = 'while-editing'  
                          textAlign="left"
                          onChangeText = {(value) => this.onChangeUsername(value)}
                          onBlur = {() => this.onBlurUsername()}
                          maxLength={18}
                          />
                    <Image style={styles.imgbg} source={require('../img/date.png')} />
                </View>

                 <View style={styles.inputText}  >
                    <TextInput
                          autoCapitalize = "none"
                          autoCorrect={false}
                          style={!this.state.passwordBool ? [styles.input,styles.inputError] : styles.input}
                          placeholder="Password" 
                          clearButtonMode = 'while-editing'
                          secureTextEntry={true}  
                          textAlign="left"
                          onChangeText = {(value) => this.onChangePassword(value)}
                          onBlur = {() => this.onBlurPassword()}
                          maxLength={18}
                          />
                    <Image style={styles.imgbg} source={require('../img/date.png')} />
                </View>

                <View ref='reg_post' style={styles.button}>
                    {postButton}
                </View>

            </View>
            <Tips ref='tips'/>
        </View>
      )
  }

 

  onChangeEmail(value) {
      this.setState({emailBool:true,email:value});
  }

  onBlurEmail() {
    if (this.state.email!== '' && Utils.isEmail(this.state.email)) {
          this.setState({emailBool:false,email:''});
          var obj = {type: 'error', msg: Lang.reg_b_email};
          this.refs['tips'].showTips(obj);
      } 
  }

  onChangeUsername(value) {
      this.setState({usernameBool:true,username:value});
  }

  onBlurUsername() {
      if (this.state.username !== '' && Utils.isLength(this.state.username,6,18)) {
          this.setState({usernameBool:false,username:''});
          var obj = {type: 'error', msg: Lang.reg_b_username};
          this.refs['tips'].showTips(obj);
      } 
  }

  onChangePassword(value) {
      this.setState({passwordBool:true,password:value});
  }

  onBlurPassword() {
      if (this.state.password !== '' && Utils.isLength(this.state.password,6,18)) {
          this.setState({passwordBool:false,password:''});
          var obj = {type: 'error', msg: Lang.reg_b_password };
          this.refs['tips'].showTips(obj);
      } 
  }
 
  checkContiune(state) {
      let bool = true;
      if (state.email == '' || Utils.isEmail(state.email)) {
          bool = false;
      } 

      if (state.username == '' || Utils.isLength(state.username,6,18)) {
          bool = false;
      } 

      if(state.password =='' || Utils.isLength(state.password,6,18)) {
          bool = false;
      } 

      this.doBool = bool;
      let color = bool ? '#56ade0' : '#999';
      this.refs['reg_post'].setNativeProps({style:{backgroundColor: color}});
  }

  handleData(obj) {
      obj.email = this.state.email;
      obj.username = this.state.username;
      obj.password = this.state.password;
      obj.facebook = true;
      obj.match_age_min = 18;
      obj.match_age_max= 99;
      return obj;
  }

  promiseDoneData(obj){     
      return new Promise(function (resolve, reject) {
          Share.fetchMain({
              url : 'register_with_img',
              data: obj,
              callback : function(data) {
                  if (typeof (data.session_id) !== 'undefined') {
                     resolve(data);
                  } else {
                     reject(data);
                  }  
              }
          });
      });
  }

  gotoLetsMeet() {
      Utils.navResetTo(this.props.navigator, {
          name: 'LetsMeet',
          component: LetsMeet,
          navBarType: 1,
          title: 'Let\'s Meet',
      })
  }

  doneSuccessful(data,that) {
      console.log('successful',data);
      that.setState({postBool : false});
      Share.setStorage('ms_user_id', data.account.usr_id);
      Share.setStorage(data.account.usr_id, JSON.stringify(data));
      that.gotoLetsMeet();
  }

  doneError(data,that){
      console.log(data);
      that.setState({postBool : false});
      if (data.tab){
          if(parseInt(data.tab) == 1){
              let arr = [],obj={};
              _.forEach(data.data, function(v,k) {    
                  if (v.error_id == 2) {
                      obj.emailBool = false;
                      arr.push(v.msg);
                  }
                  if (v.error_id == 1) {
                      obj.usernameBool = false;
                      arr.push(v.msg);
                  }
                  if (v.error_id == 3) {
                      obj.passwordBool = false;
                      arr.push(v.msg);
                  }          
              });
              that.setState(obj);
              var obj = {type: 'errors', msg: arr};
              that.refs['tips'].showTips(obj);
          }
      }
  }
  
  done() {
      if (this.doBool) {
          this.setState({postBool : true});
          let that = this;
          Share.promiseGetStoreData('register')
          .then(function(value){
              let obj = JSON.parse(value);
              return that.handleData(obj); 
          })
          .then(this.promiseDoneData)
          .then(function(data){
            that.doneSuccessful(data,that);
          },function(data){
            that.doneError(data,that);
          })
          .catch((error) => console.log(error));  
      } 
  }
}

const styles = StyleSheet.create(Css.RegisterBStyle);

export default RegisterB;
